﻿using Abp.Application.Services;
using Batman.Cache;
using Batman.Cache.Attributes;
using Batman.Cms.Core.Const;
using Batman.Jianbei.Forum.Core.Datas;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Batman.Jianbei.Forum.Services.Users
{
    public class RoleCacheService : IApplicationService, ICacheWorkable
    {
        /// <summary>
        /// 获取全部管理员或者超级管理员用户ID
        /// </summary>
        /// <returns></returns>
        [Cacher(CacheSeconds = 1800)]
        public virtual List<string> GetAdminOrSupperAdminIds()
        {
            using (var ctx = new JianbeiForumDbContextFactory().CreateDbContext(null))
            {
                var adminOrSuperAdmin = new string[] { SysRole.ADMIN, SysRole.SUPER_ADMIN };
                var roleQuery = ctx.Roles.AsNoTracking().Where(t => adminOrSuperAdmin.Contains(t.NormalizedName));

                var userRoleQuery = ctx.UserRoles.AsNoTracking();

                var joinQuery = userRoleQuery.Join(roleQuery, ur => ur.RoleId, r => r.Id, (userRole, role) => userRole.UserId);

                var result = joinQuery.ToList();

                return result;
            }
        }

        /// <summary>
        /// 获取全部管理员或者超级管理员用户UID(微信表ID)
        /// </summary>
        /// <returns></returns>
        [Cacher(Id = CacheNames.AdminOrSupperAdminUids)]
        public virtual List<string> GetAdminOrSupperAdminUids()
        {
            var adminIds = GetAdminOrSupperAdminIds();
            using (var ctx = new DbContextFactory().CreateDbContext(null))
            {
                var result = ctx.WeixinUser.AsNoTracking().Where(t => adminIds.Contains(t.UserId)).Select(t => t.Id).ToList();
                return result;
            }

        }
    }
}
